using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using WindowsLive.Writer.Api;

namespace Watchwords
{
    [WriterPlugin
     ( "3473682A-572F-4730-ACB6-CAE3329E3DD3",
        "Watchwords Plugin",
        ImagePath = "Images.WatchwordIcon.png",
        PublisherUrl = "http://thopark.spaces.live.com/",
        HasEditableOptions = true,
        Description = "Add daily watchwords to your blog" )]

    [InsertableContentSourceAttribute ( "Watchword" )]
    public class Plugin : ContentSource
    {
        private WatchwordSettings Properties;

        public override void Initialize( IProperties pluginOptions )
        {
            base.Initialize ( pluginOptions );
            Properties = new WatchwordSettings ( pluginOptions );            
        }

        public override void EditOptions( IWin32Window dialogOwner )
        {
            OptionsDialog d = new OptionsDialog ();
            d.SelectedLanguage = Properties.Language;
            DialogResult r = d.ShowDialog ();
            if (r == DialogResult.OK)
            {
                Properties.Language = d.SelectedLanguage;
            }
        }

        public override DialogResult CreateContent( IWin32Window dialogOwner, ref string newContent )
        {
            string Content = string.Empty;

            string URL = "http://www.losung.de/cgi-bin/today.pl?inline=2";

            if (Properties.Language.Length > 0)
            {
                URL += "&lang=" + Properties.Language;
            }

            if (
                (Properties.CacheLanguage == Properties.Language)
                &&
                (Properties.CacheDate.Date == DateTime.Today)
                )
            {
                Content = Properties.CacheString;
            }
            else
            {
                try
                {
                    System.Net.WebRequest req = System.Net.WebRequest.Create ( URL );
                    req.Timeout = 5000;
                    System.Net.WebResponse res = req.GetResponse ();

                    System.IO.StreamReader r = new System.IO.StreamReader ( res.GetResponseStream (), Encoding.GetEncoding ( "ISO-8859-15" ) );
                    Content = r.ReadToEnd ();
                    r.Close ();
                    Properties.CacheString = Content;
                    Properties.CacheDate = DateTime.Today;
                    Properties.CacheLanguage = Properties.Language;
                }
                catch
                {
                    WindowsLive.Writer.Api.PluginDiagnostics.DisplayError ( "Error requesting Watchwords server",
                        "Todays Watchwords couldn't be fetched from " + URL + " within 5 seconds." );
                }
            }

            newContent = Content;

            return DialogResult.OK;
        }
    }
}
